package com.xiaoluyy.demo.common.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpNewClient {

        private static Logger log = LoggerFactory.getLogger(HttpClient.class);

        static RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(600)
                .setConnectTimeout(600)
                .setConnectionRequestTimeout(600)
                .setStaleConnectionCheckEnabled(true)
                .build();

    public static HttpResult post(String url, Map<String, String> params) {
        HttpResult result = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
            String body = null;

            log.info("HttpNewClient create httppost:" + url);
            HttpPost post = postForm(url, params);

            result = invoke(httpClient, post);

        } catch (Exception e) {
            log.error("HttpNewClient invoke post failed,url:" + url + ",data:" + JSON.toJSONString(params), e);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("HttpNewClient close failed,url:" + url + ",data:" + JSON.toJSONString(params), e);
            }
        }

        return result;
    }

    public static HttpResult get(String url) {

        HttpResult result = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
            log.info("HttpNewClient create httpget:" + url);
            HttpGet get = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
            get.setConfig(requestConfig);
            result = invoke(httpClient, get);

        } catch (Exception e) {
            log.error("HttpNewClient invoke get failed,url:" + url, e);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("HttpNewClient close failed,url:" + url, e);
            }
        }

        return result;
    }


    private static HttpResult invoke(org.apache.http.client.HttpClient httpclient,
                                     HttpUriRequest httpost) {

        HttpResponse response = sendRequest(httpclient, httpost);
        HttpResult result = paseResponse(response);

        return result;
    }

    private static HttpResult paseResponse(HttpResponse response) {

        HttpResult result = new HttpResult();
        if (response == null || response.getStatusLine() == null || response.getEntity() == null) {
            result.setStatusCode(500);
            result.setBody("HttpNewClient response return null.");
            return result;
        }
        result.setStatusCode(response.getStatusLine().getStatusCode());
        log.info("HttpNewClient get response from http server.." + " response code:" + result.getStatusCode());
        HttpEntity entity = response.getEntity();

        log.info("HttpNewClient response status: " + response.getStatusLine());
        String charset = EntityUtils.getContentCharSet(entity);
        log.info("HttpNewClient response charset:" + charset);

        String body = null;
        try {
            body = EntityUtils.toString(entity, "UTF-8");
            result.setBody(body);
            log.info("HttpNewClient paseResponse body:" + body);
        } catch (Exception e) {
            log.error("HttpNewClient paseResponse failed due to Exception,", e);
        }
        return result;
    }

    private static HttpResponse sendRequest(org.apache.http.client.HttpClient httpclient,
                                            HttpUriRequest httpost) {
        log.info("HttpNewClient execute post...");
        HttpResponse response = null;

        try {
            response = httpclient.execute(httpost);
        } catch (ClientProtocolException e) {
            log.error("HttpNewClient sendRequest failed due to ClientProtocolException,", e);
        } catch (IOException e) {
            log.error("HttpNewClient sendRequest failed due to IOException,", e);
        }
        return response;
    }

    private static HttpPost postForm(String url, Map<String, String> params) {

        HttpPost httpost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpost.setConfig(requestConfig);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }

        try {
            log.info("HttpNewClient set utf-8 form entity to httppost");
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("HttpNewClient postForm set encoding failed,", e);
        }

        return httpost;
    }

    public static class HttpResult {
        private Integer statusCode;

        private String body;

        public Integer getStatusCode() {
            return statusCode;
        }

        public void setStatusCode(Integer statusCode) {
            this.statusCode = statusCode;
        }

        public String getBody() {
            return body;
        }

        public void setBody(String body) {
            this.body = body;
        }

    }



}
